<template>
	<view class="container-page">
		<u-avatar shape="square" size="180rpx" src="/static/images/wx.png" customStyle="margin-top: 100rpx"></u-avatar>
		<view class="t36 mt64">微信授权页面</view>
		<view class="t28 c-content mt32">授权并同意使用微信账号登录当前小程序</view>
		<view class="t28 mt64 flex-center">
			<radio name="" label="" :checked="isAgree" @click="isAgree=!isAgree">已阅读并同意</radio>
			<u-link href="/pages/article/index?key=yhxy" text="《用户协议》"></u-link>
		</view>
			
		<u-button type="success" text="授权登录" @click="goNextPage" class="mt32"></u-button>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				isAgree: false
			}
		},
		created() {

		},
		mounted() {

		},
		onReady() {

		},
		onLoad(e) {
			if(uni.getStorageSync('token')){
				uni.reLaunch({
					url: '/pages/index/index',
				});
			}
		},
		onShow() {

		},
		methods: {
			async _wxlogin(code) {
				const res = await this.$wxapi.wxlogin(code)
				if (res.code == 200) {
					uni.setStorageSync('token',res.token)//getApp().globalData.token=res.data.tokenHead+res.data.token;//uni.setStorageSync('token',res.token)
					uni.reLaunch({
						url: '/pages/index/index',
					});
				} else {
					uni.showToast({
						title: res.msg,
						icon: 'none'
					})
				}
			},
			async _login() {
				const res = await this.$wxapi.login('test','123456')
				if (res.code == 200) {
					uni.setStorageSync('token',res.token)//getApp().globalData.token=res.data.tokenHead+res.data.token;//
					uni.reLaunch({
						url: '/pages/index/index',
					});
					uni.close
				} else {
					uni.showToast({
						title: res.msg,
						icon: 'none'
					})
				}
			},
			goNextPage() {
				if (!this.isAgree) {
					uni.showToast({
						title: '请先同意'
					});
					return
				}
				// #ifdef MP
				uni.login({
					"provider": "weixin",
					"onlyAuthorize": true, // 微信登录仅请求授权认证
					success: function(event){
						const {code} = event
						//客户端成功获取授权临时票据（code）,向业务服务器发起登录请求。
						this._wxlogin(code)
					},
					fail: function (err) {
						uni.showToast({
							title: '登录授权失败:'+err.code,
							icon: 'none'
						})
				    }
				})
				// #endif
				// #ifndef MP
				this._login()
				// #endif
			},
			goUrl(url) {
				if (url) {
					uni.navigateTo({
						url
					})
				}
			},
			
		}
	}
</script>
<style scoped lang="scss">
.container-page {
	display: flex;
	flex-direction: column;
	flex-wrap: wrap;
	justify-content: space-between;
	align-items: center;
	padding: 64rpx;
}
</style>
